package com.oriole.api.config;

import com.oriole.api.config.security.local.TokenProvider;
import com.oriole.api.module.sys.service.ISysUserService;
import com.oriole.common.constant.Constants;
import com.oriole.entity.sys.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/1 10:52
 * description: Jpa审计，@CreatedBy @LastModifiedBy的值
 */
@Component
public class JpaAuditorAware implements AuditorAware<Long> {

    @Resource
    private ISysUserService sysUserService;

    @Override
    public Optional<Long> getCurrentAuditor() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            return Optional.empty();
        }
        if (ctx.getAuthentication() == null) {
            return Optional.empty();
        }
        if (ctx.getAuthentication().getPrincipal() == null) {
            return Optional.empty();
        }
        Object principal = ctx.getAuthentication().getPrincipal();
        Object token = ctx.getAuthentication().getCredentials();
        TokenProvider tokenProvider = new TokenProvider();
        Object userId = tokenProvider.getToken(token.toString(), Constants.USER_ID);
        if (StringUtils.isNotBlank(userId.toString())) {
            return Optional.of(Long.parseLong(userId.toString()));
        }
        if (principal.getClass().isAssignableFrom(String.class)) {
            return Optional.of(0L);
        } else {
            return Optional.empty();
        }
    }
}
